<template>
  <a-modal
    :title="$t('all.autotext986')"
    :visible="visible"
    @ok="onSubmit"
    @cancel="cancel"
  >
    <a-table
      ref="table"
      size="default"
      :rowKey="record => record.id"
      :columns="columns"
      :data-source="dataTable"
      :pagination="false"
    >
      <template slot="researchName" slot-scope="text, record">
        <span>{{ record.researchCenterNo }}-{{ record.researchName }}</span>
      </template>
      <template slot="amount" slot-scope="text, record">
        <a-input-number
          v-model.trim="record.amount"
          class="amount-number"
          :min="0"
          :precision="2"
        />
      </template>
    </a-table>
  </a-modal>
</template>
<script>
import { researchCostList, updateResearchCost } from '@/api/project/configItem/cost'

export default {
  props: ['visible', 'item', 'configId'],
  data () {
    return {
      columns: [
        {
          title: this.$t('all.autotext334'),
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: this.$t('all.autotext949'),
          key: 'researchName',
          dataIndex: 'researchName',
          scopedSlots: { customRender: 'researchName' }
        },
        {
          title: this.$t('all.autotext750'),
          key: 'amount',
          dataIndex: 'amount',
          scopedSlots: { customRender: 'amount' }
        }
      ],
      oldDate: [],
      dataTable: []
    }
  },
  watch: {
    visible (val) {
      if (!val) return
      this.getResearchCostList()
    }
  },
  methods: {
    async getResearchCostList () {
      const res = await researchCostList({ costId: this.item.id, configId: this.configId })
      this.oldDate = JSON.parse(JSON.stringify(res))
      this.dataTable = res
    },
    async onSubmit () {
      let list = []
      if (this.dataTable.some(v => !v.amount && v.amount !== 0)) {
        this.$message.error(this.$t('all.autotext1804'))
        return
      }
      this.dataTable.forEach((item, i) => {
        if (Number(this.oldDate[i].amount) !== Number(item.amount)) {
          list.push({
            researchId: item.researchId,
            costId: this.item.id,
            proId: item.proId,
            amount: item.amount,
            applyType: this.item.applyType,
            configId: this.configId
          })
        }
      })
      if (list.length === 0) return this.cancel()
      await updateResearchCost(list)
      this.$message.success(this.$t('all.autotext1431'))
      this.cancel()
    },
    cancel () {
      this.$emit('update:visible', false)
    }
  }
}
</script>
<style lang="less" scoped>
.amount-number {
  width: 100px;
}
</style>
